package com.geh.learn.hutool;

import cn.hutool.crypto.symmetric.AES;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptAesTest {

    /**
     * AES加密
     *
     * @param aesKey 密钥
     * @param text 明文
     * @return 密文
     */
    public static String encryptAes(String aesKey, String text) {
        try {
            byte[] key = aesKey.getBytes(Charsets.UTF_8);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptBytes = cipher.doFinal(text.getBytes(Charsets.UTF_8));
            // Base64一下，解密的时候先解码
            return BaseEncoding.base64().encode(encryptBytes);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * AES解密
     *
     * @param aesKey 密钥
     * @param text 密文
     * @return 明文
     */
    public static String decryptAes(String aesKey, String text) {
        try {
            byte[] key = aesKey.getBytes(Charsets.UTF_8);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptBytes = cipher.doFinal(BaseEncoding.base64().decode(text));
            return new String(decryptBytes, Charsets.UTF_8);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String original = "Hello World!";
        String password = "Passw0rd";
        System.out.println("original = " + original);
        System.out.println("password = " + password);



        // md5一下，正好32位，32*8 = 256 个byte，aes 256加密的意思
        String passwordMd5 =  Hashing.md5().hashString(password, Charsets.UTF_8).toString();

        AES aes = new AES(passwordMd5.getBytes(Charsets.UTF_8));
        String hutoolAes = aes.encryptBase64(original);

        System.out.println("hutoolAes " + hutoolAes);

        System.out.println("hutoolAesDecrypt " + aes.decryptStr(hutoolAes));

        String encyptedText = encryptAes(passwordMd5, original);
        System.out.println("encryptAes = " + encyptedText);
        System.out.println("decryptAes = " + decryptAes(passwordMd5, encyptedText));
    }

}
